package com.kust.smarthome.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kust.smarthome.web.dto.PersonDetailsDto;
import com.kust.smarthome.web.mapper.PersonDetailsMapper;
import com.kust.smarthome.web.mapper.RelationMapper;
import com.kust.smarthome.web.model.PersonDetails;
import com.kust.smarthome.web.model.Relation;
import com.kust.smarthome.web.service.IRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author iAuzre
 * @since 2021-07-06
 */
@Service
public class RelationServiceImpl extends ServiceImpl<RelationMapper, Relation> implements IRelationService {

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private PersonDetailsMapper personDetailsMapper;


    @Override
    public int insert(Relation relation) {
        relationMapper.insert(relation);
        return relation.getId();
    }

    @Override
    public List<Relation> relationListByUser(Integer userId) {
        QueryWrapper<Relation> query = new QueryWrapper<>();
        query.eq("user_id", userId);

        List<Relation> list = relationMapper.selectList(query);

        return list;
    }

    @Override
    public List<PersonDetails> findPersonDetailsByUser(Integer userId) {
        return personDetailsMapper.selectPersonDetailsByUser(userId);
    }

    @Override
    @Transactional
    public boolean removeRelation(Integer userId, Integer relationId) {

        Relation relation = relationMapper.selectById(relationId);

        QueryWrapper<PersonDetails> query = new QueryWrapper<>();
        query.eq("user_id", userId)
                .eq("relation_id", relationId);

        if (relation.getUserId() == userId) {
            personDetailsMapper.delete(query);
            return relationMapper.deleteById(relationId) == 1;
        }

        return false;
    }


}
